import {reactive, ref} from 'vue'
import {registerApi} from '@/api'
import { validateForm } from '@/utils/validateForm'
export function useRegisterData() {
    const loading = ref(false)
    const loginFormRef = ref(null)
    const loginForm = reactive({
        username: '',
        password: ''
    })
    const pwdState = reactive({
        icon: 'eye-fill',
        type: 'password'
    })
    const handleToLogin = () => {
        uni.navigateTo({
            url: '/pages/login/login'
        })
    }

    function handleToRegister() {
        validateForm(loginFormRef, register)
    }

    function register() {
        loading.value = true
        registerApi(loginForm).then(res => {
           uni.showToast({ title: res.msg || '注册成功', icon: 'none', duration: 2000 })
           uni.navigateTo({ url: '/pages/login/login' })

        }).finally(_ => {
            loading.value = false
        })
    }

    function handlePwdInput() {
        pwdState.type = pwdState.type === 'text' ? 'password' : 'text'
        pwdState.icon = pwdState.icon === 'eye-fill' ? 'eye-off' : 'eye-fill'
    }

    return {
        loginForm,
        handleToRegister,
        handleToLogin,
        loading,
        pwdState,
        handlePwdInput,
        loginFormRef
    }
}